﻿using Microsoft.Owin.Security.Infrastructure;
using System;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Linq;
using Common.JWT;
using System.Configuration;

namespace OAuthServerApi
{
    public class CustomAccessTokenProvider : AuthenticationTokenProvider
    {
        public IJsonToken jsonToken = new JsonToken();
        public static readonly string jwtSignKey = ConfigurationManager.AppSettings["JwtSignKey"];
        public static readonly string signKey = ConfigurationManager.AppSettings["HMSHA1Key"];
        public CustomAccessTokenProvider()
        {
        }
        public override async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            try
            {
                var claims = context.Ticket.Identity.Claims;
                if (claims.Where(x => x.Type == CustomClaimsType.RequestUniqueId).Count() == 0)
                {
                    context.Ticket.Identity.AddClaim(new Claim(CustomClaimsType.RequestUniqueId, Guid.NewGuid().ToString("n")));
                }
                var customClaims = claims.Where(x => x.Type.StartsWith("as:")).Select(x => new
                {
                    x.Type,
                    x.Value
                });
                //claim信息
                var client = customClaims.FirstOrDefault(x => x.Type == CustomClaimsType.ClientId);
                var user = customClaims.FirstOrDefault(x => x.Type == CustomClaimsType.UserId);
                var grant = customClaims.FirstOrDefault(x => x.Type == CustomClaimsType.GrantType);
                var ticket = JwtHelper.MD5(string.Join(".", customClaims), 32);
                var tokenModel = new OAuthToken
                {
                    AccessToken = string.Empty,
                    ClientHash = client == null ? string.Empty : client.Value,
                    UserHash = user == null ? string.Empty : user.Value,
                    ExperiesDate = DateTime.Now.AddSeconds(AppConstNum.expires_in_second),
                    GrantType = grant == null ? 0 : int.Parse(grant.Value),
                    Ticket = string.Empty,
                    RefreshToken = string.Empty
                };
                //var token = JwtHelper.(JwtHashAlgorithm.HS256, signKey)(ticket);
                var token = jsonToken.Encode(ticket, jwtSignKey);
                //生成token
                tokenModel.AccessToken = token;
                //设置环境AccessToken
                context.OwinContext.Set(OwinEnvType.AccessToken, tokenModel);
                context.SetToken(token);
                await base.CreateAsync(context);
            }
            catch
            {
                throw new AggregateException("生成token失败");
            }
        }
    }
}